// -----------------------------------------------------------------------
//  <copyright file="WeightSlaveDatabaseSelector.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2022 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2022-11-08 21:57</last-date>
// -----------------------------------------------------------------------

using DaprPlus.EntityFrameworkCore.Properties;


namespace DaprPlus.EntityFrameworkCore;

/// <summary>
/// 平滑权重从数据库选择器
/// </summary>
public class WeightSlaveDatabaseSelector : ISlaveDatabaseSelector
{
    private static readonly object Locker = new();
    private readonly ILogger _logger;
    private Queue<int> _queue = new();

    /// <summary>
    /// 初始化一个<see cref="WeightSlaveDatabaseSelector"/>类型的新实例
    /// </summary>
    public WeightSlaveDatabaseSelector(IServiceProvider serviceProvider)
    {
        _logger = serviceProvider.GetLogger<WeightSlaveDatabaseSelector>();
    }

    /// <summary>
    /// 获取 名称
    /// </summary>
    public string Name => "Weight";

    /// <summary>
    /// 从所有从数据库中选择一个
    /// </summary>
    public SlaveDatabaseOptions Select(SlaveDatabaseOptions[] slaves)
    {
        Check.NotNullOrEmpty(slaves, nameof(slaves));

        lock (Locker)
        {
            if (_queue.Count == 0)
            {
                _queue = GetIndexes(slaves);
            }

            var index = _queue.Dequeue();
            var slave = slaves[index];
            _logger.LogInformation(ResEFCore.Format_Entity_SelectSlave_Weight, slave.Name, slave.Weight);
            return slave;
        }
    }

    private static Queue<int> GetIndexes(SlaveDatabaseOptions[] slaves)
    {
        var wraps = slaves.Select(m => new SlaveDatabaseOptionsWrap(m)).ToArray();
        var sum = wraps.Sum(m => m.Weight);
        var queue = new Queue<int>();
        for (var i = 0; i < sum; i++)
        {
            var index = NextIndex(wraps);
            queue.Enqueue(index);
        }

        return queue;
    }

    private static int NextIndex(SlaveDatabaseOptionsWrap[] wraps)
    {
        int index = -1, total = 0;
        for (var i = 0; i < wraps.Length; i++)
        {
            var wrap = wraps[i];
            wrap.Current += wrap.Weight;
            total += wrap.Weight;
            if (index == -1 || wraps[index].Current < wrap.Current)
            {
                index = i;
            }
        }

        wraps[index].Current -= total;
        return index;
    }


    private class SlaveDatabaseOptionsWrap : SlaveDatabaseOptions
    {
        public SlaveDatabaseOptionsWrap(SlaveDatabaseOptions slave)
        {
            Weight = slave.Weight;
        }

        /// <summary>
        /// 获取或设置 当前权重
        /// </summary>
        public int Current { get; set; }
    }
}
